package com.sinodata.ns.cell;

import jt.classic.system.ISystem;
import jt.classic.system.SimpleAction;
import jt.classic.system.database.SystemDataSource;
import jt.classic.system.user.IUser;

import net.sf.json.JSONArray;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import org.limp.basework.impl.CommonBean4HSQ;
import org.limp.basework.tools.BaseworkUtil;

import org.limp.mine.DataTrimmerI;
import org.limp.mine.DataTrimmerI.DataItemList;
import org.limp.mine.Label;
import org.limp.mine.QueryJack;
import org.limp.mine.QueryJackFactory;
import org.limp.mine.StringTool;

import java.sql.Connection;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * 监理标段控制器
 *
 * @author mido
 *
 */
public class JLBDAction extends SimpleAction {
    /**
        * 管理列表
        * @param mapping
        * @param form
        * @param request
        * @param response
        * @return
        * @throws Exception
        */
    public ActionForward list(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        CommonBean4HSQ req = new CommonBean4HSQ(request);

        Map param = req.getResource();

        String pageNO = StringTool.checkString(param.get("pageNO"));

        String start = StringTool.checkString(param.get("start"), "0");

        String size = StringTool.checkString(param.get("limit"), "20");

        pageNO = String.valueOf((Integer.parseInt(start) / Integer.parseInt(
                    size)) + 1);

        StringBuffer where = new StringBuffer(" WHERE 1 = 1 ");

        String cname = StringTool.checkString(param.get("cname"));

        if (!cname.equals("")) {
            where.append(" AND SVBD_NAME LIKE '%" + cname + "%' ");
        }

        String cunit = StringTool.checkString(param.get("cunit"));

        if (!cunit.equals("")) {
            where.append(" AND SVBD_GROUPID = '" + cunit + "' ");
        }

        String ctype = StringTool.checkString(param.get("ctype"));

        if (!ctype.equals("")) {
            //where.append(" AND C_TYPE LIKE '%" + ctype + "%' ");
        }

        String carea = StringTool.checkString(param.get("carea"));

        if (!carea.equals("")) {
            //where.append(" AND C_AREA LIKE '%" + carea + "%' ");
        }

        String sql1 = "SELECT COUNT(*) FROM APP_NS_SVBD " + where.toString();

        String sql2 = "SELECT * FROM APP_NS_SVBD " + where.toString() +
            " ORDER BY SVBD_NAME";

        String url = jt.classic.system.ISystem.getContextPath() +
            "/app/jlbdaction.do?method=list";

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            QueryJack plus = QueryJackFactory.getInstance().createQueryJack(false);

            plus.setParameter(QueryJackFactory.PAGINATION_SQL1, sql1);
            plus.setParameter(QueryJackFactory.PAGINATION_SQL2, sql2);
            plus.setParameter(QueryJackFactory.DATABASE_CONNECTION, conn);
            plus.setParameter(QueryJackFactory.PAGINATION_LINKSTRING, url);
            plus.setParameter(QueryJackFactory.PAGINATION_COUNT, size);
            plus.setParameter(QueryJackFactory.PAGINATION_PAGENO, pageNO);

            // plus.setParameter(QueryJackFactory.PAGINATION_UPDATEPAGENO, "");
            List resultList = plus.work();

            if ((resultList != null) && !resultList.isEmpty()) {
                JLBDManager jm = new JLBDManager(conn);

                for (int i = 0; i < resultList.size(); i++) {
                    Map map = (Map) resultList.get(i);
                    String id = (String) map.get("ID");
                    JLBDInfo info = jm.getJLBDInfoById(id);

                    map.put("SVBD_GROUPID",
                        (info.igroup() != null) ? info.igroup().id() : "");
                    map.put("SVBD_GROUP",
                        (info.igroup() != null) ? info.igroup().iname() : "");
                    map.put("C_NAME",
                        ((info.icell() != null) ? info.icell().iname() : ""));
                    map.put("C_UNIT",
                        ((info.icell() != null) ? info.icell().iunit() : ""));
                    map.put("C_TYPE",
                        ((info.icell() != null) ? info.icell().itype() : ""));
                    map.put("C_AREA",
                        ((info.icell() != null) ? info.icell().iarea() : ""));

                    List list = info.icell().ibd();

                    if ((list != null) && !list.isEmpty()) {
                        StringBuffer bdids = new StringBuffer();
                        StringBuffer bdnames = new StringBuffer();

                        for (int j = 0; j < list.size(); j++) {
                            CellBDInfo cbi = (CellBDInfo) list.get(j);

                            if (j < (list.size() - 1)) {
                                bdids.append(cbi.id() + ",");
                                bdnames.append(cbi.iname() + ",");
                            } else {
                                bdids.append(cbi.id());
                                bdnames.append(cbi.iname());
                            }
                        }

                        map.put("CB_ID", bdids.toString());
                        map.put("CB_NAME", bdnames.toString());
                    }
                }
            }

            Label label = plus.getLabel();

            JSONArray jsonArray = JSONArray.fromObject(resultList);

            String jsonString = "{\"pageNO\":\"" + label.current() +
                "\",\"totalPage\":\"" + label.totalfan() +
                "\",\"totalCount\":\"" + label.totaldata() +
                "\",\"queryList\":";
            jsonString += jsonArray.toString();
            jsonString += "}";

            request.setAttribute("result", jsonString);
        } catch (Exception ex) {
            request.setAttribute("result", "{success: false}");
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("jsonresult");
    }

    /**
     * 监理标段(会话用户可以选择的)列表
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    public ActionForward mylist(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        IUser user = ISystem.getSessionUser(request);

        CommonBean4HSQ req = new CommonBean4HSQ(request);

        Map param = req.getResource();

        String pageNO = StringTool.checkString(param.get("pageNO"));

        String start = StringTool.checkString(param.get("start"), "0");

        String size = StringTool.checkString(param.get("limit"), "20");

        pageNO = String.valueOf((Integer.parseInt(start) / Integer.parseInt(
                    size)) + 1);

        StringBuffer where = new StringBuffer(" WHERE SVBD_GROUPID = '" +
                ((user.igroup() != null) ? user.igroup().id() : "0") + "' ");

        String sql1 = "SELECT COUNT(*) FROM APP_NS_SVBD " + where.toString();

        String sql2 = "SELECT * FROM APP_NS_SVBD " + where.toString() +
            " ORDER BY SVBD_NAME";

        String url = jt.classic.system.ISystem.getContextPath() +
            "/app/jlbdaction.do?method=list";

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            QueryJack plus = QueryJackFactory.getInstance().createQueryJack(false);

            plus.setParameter(QueryJackFactory.PAGINATION_SQL1, sql1);
            plus.setParameter(QueryJackFactory.PAGINATION_SQL2, sql2);
            plus.setParameter(QueryJackFactory.DATABASE_CONNECTION, conn);
            plus.setParameter(QueryJackFactory.PAGINATION_LINKSTRING, url);
            plus.setParameter(QueryJackFactory.PAGINATION_COUNT, size);
            plus.setParameter(QueryJackFactory.PAGINATION_PAGENO, pageNO);

            // plus.setParameter(QueryJackFactory.PAGINATION_UPDATEPAGENO, "");
            List resultList = plus.work();

            if ((resultList != null) && !resultList.isEmpty()) {
                JLBDManager jm = new JLBDManager(conn);

                for (int i = 0; i < resultList.size(); i++) {
                    Map map = (Map) resultList.get(i);
                    String id = (String) map.get("ID");
                    JLBDInfo info = jm.getJLBDInfoById(id);

                    map.put("SVBD_GROUP",
                        (info.igroup() != null) ? info.igroup().iname() : "");
                    map.put("C_NAME",
                        ((info.icell() != null) ? info.icell().iname() : ""));
                    map.put("C_UNIT",
                        ((info.icell() != null) ? info.icell().iunit() : ""));
                    map.put("C_TYPE",
                        ((info.icell() != null) ? info.icell().itype() : ""));
                    map.put("C_AREA",
                        ((info.icell() != null) ? info.icell().iarea() : ""));

                    List list = info.icell().ibd();

                    if ((list != null) && !list.isEmpty()) {
                        StringBuffer bdids = new StringBuffer();
                        StringBuffer bdnames = new StringBuffer();

                        for (int j = 0; j < list.size(); j++) {
                            CellBDInfo cbi = (CellBDInfo) list.get(j);

                            if (j < (list.size() - 1)) {
                                bdids.append(cbi.id() + ",");
                                bdnames.append(cbi.iname() + ",");
                            } else {
                                bdids.append(cbi.id());
                                bdnames.append(cbi.iname());
                            }
                        }

                        map.put("CB_ID", bdids.toString());
                        map.put("CB_NAME", bdnames.toString());
                    }
                }
            }

            Label label = plus.getLabel();

            JSONArray jsonArray = JSONArray.fromObject(resultList);

            String jsonString = "{\"pageNO\":\"" + label.current() +
                "\",\"totalPage\":\"" + label.totalfan() +
                "\",\"totalCount\":\"" + label.totaldata() +
                "\",\"queryList\":";
            jsonString += jsonArray.toString();
            jsonString += "}";

            request.setAttribute("result", jsonString);
        } catch (Exception ex) {
            request.setAttribute("result", "{success: false}");
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("jsonresult");
    }

    /**
     * 更新监理标段信息
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     * @throws Exception
     */
    public ActionForward update(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        IUser user = ISystem.getSessionUser(request);

        CommonBean4HSQ req = new CommonBean4HSQ(request);

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            BaseworkUtil util = new BaseworkUtil();

            Map map1 = (Map)util.manualDelete("APP_NS_SVBDITEM", request, conn);
            Map map2 = (Map)util.manualUpdate("APP_NS_SVBD", request, conn);
            util.manualSaveX("APP_NS_SVBDITEM", "counterName", request, conn);

            conn.commit();

            request.setAttribute("result", "{success: true}");
        } catch (Exception ex) {
            conn.rollback();
            request.setAttribute("result", "{success: false}");
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("result");
    }

    /**
     * 删除监理标段信息
     * @param mapping
     * @param form
     * @param request
     * @param response
     * @return ActionForward
     * @throws Exception
     */
    public ActionForward delete(ActionMapping mapping, ActionForm form,
        HttpServletRequest request, HttpServletResponse response)
        throws Exception {
        Connection conn = null;

        IUser user = ISystem.getSessionUser(request);

        CommonBean4HSQ req = new CommonBean4HSQ(request);

        String id = (String) req.getResource().get("ID");

        try {
            SystemDataSource ds = SystemDataSource.getInstance();
            conn = ds.getConnection();

            BaseworkUtil util = new BaseworkUtil();

            util.manualDelete("APP_NS_SVBDITEM", request, conn);
            util.manualDelete("APP_NS_SVBD", request, conn);

            String sql = "UPDATE APP_NS_JLRY SET NU_BD = ?, NU_BDID = ? WHERE NU_BDID = ?";

            DataTrimmerI trimmer = new DataTrimmerI(conn);

            DataItemList dil = trimmer.createDIL();

            dil.set("");
            dil.set(0);
            dil.set(id);

            if (trimmer.execute(sql, dil)) {
                conn.commit();
                request.setAttribute("result", "{success: true}");
            } else {
                request.setAttribute("result", "{success: false}");
            }
        } catch (Exception ex) {
            conn.rollback();
            request.setAttribute("result", "{success: false}");
            ISystem.catchException(request, this, ex);
        } finally {
            SystemDataSource.closeConnection(conn);
        }

        return mapping.findForward("result");
    }
}
